package crazymakercircle;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: DRevelation
 * @Date: 2021/7/20 13:41
 */
@Slf4j
public class NettyDiscardServer {

    private final int port;

    public NettyDiscardServer(int port) {
        this.port = port;
    }

    ServerBootstrap bootstrap = new ServerBootstrap();

    public void run() {
        // 创建反应器轮询组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //1.设置反应器轮询组
            bootstrap.group(bossGroup, workerGroup)
                    //2.设置Nio类型的通道
                    .channel(NioServerSocketChannel.class)
                    //3.设置监听端口
                    .localAddress(port)
                    //4.设置通道的参数
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    //5.装配子通道流水线
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 有连接到达是会创建一个通道
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 流水线的职责：负责管理通道中的 Handler 处理器
                            // 向“子通道”（传输通道）流水线添加一个 handler 处理器
                            ch.pipeline().addLast(new NettyDiscardHandler());
                        }
                    });
            // 6 开始绑定服务器
            // 通过调用 sync 同步方法阻塞直到绑定成功
            ChannelFuture channelFuture = bootstrap.bind().sync();
            log.info("服务器启动，监听端口：" + channelFuture.channel().localAddress());
            // 7 等待通道关闭的异步任务结束
            // 服务监听通道会一直等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyDiscardServer server = new NettyDiscardServer(18080);
        server.run();
    }

}
